2.1 NumPy基础
🎯 学习目标
通过成绩分析器项目,掌握NumPy数组操作和数学运算
📝 项目预览:成绩分析器
我们将创建一个能够进行学生成绩统计和分析的工具,通过这个项目学习:
- NumPy数组的创建和操作
- 数组的数学运算和统计
- 向量化运算的优势
- 条件筛选和数据过滤
- 多维数组操作
1. NumPy简介
什么是NumPy?
NumPy是Python中用于科学计算的核心库,提供了强大的多维数组对象和数学函数。
为什么需要NumPy?
- 高效:比Python列表快很多
- 方便:提供了丰富的数学函数
- 标准:是很多科学计算库的基础
安装NumPy
pip install numpy2. 数组基础
创建数组
import numpy as np
# 从列表创建数组
scores = np.array([85, 92, 78, 96, 88])
print("成绩数组:", scores)
# 创建全0数组
zeros = np.zeros(5)
print("全0数组:", zeros)
# 创建全1数组
ones = np.ones(5)
print("全1数组:", ones)
# 创建等差数列
range_array = np.arange(0, 10, 2) # 0,2,4,6,8
print("等差数列:", range_array)数组属性
scores = np.array([85, 92, 78, 96, 88])
print("数组形状:", scores.shape) # (5,) - 5个元素的一维数组
print("数组维度:", scores.ndim) # 1 - 一维数组
print("数组大小:", scores.size) # 5 - 元素总数
print("数据类型:", scores.dtype) # int64 - 整数类型3. 数组索引和切片
基本索引
scores = np.array([85, 92, 78, 96, 88])
print("第一个成绩:", scores[0]) # 85
print("最后一个成绩:", scores[-1]) # 88
print("第二个成绩:", scores[1]) # 92切片操作
scores = np.array([85, 92, 78, 96, 88])
print("前三个成绩:", scores[:3]) # [85, 92, 78]
print("后两个成绩:", scores[-2:]) # [96, 88]
print("第2到第4个成绩:", scores[1:4]) # [92, 78, 96]
print("每隔一个取一个:", scores[::2]) # [85, 78, 88]4. 数学运算
基本数学运算
scores = np.array([85, 92, 78, 96, 88])
print("最高分:", np.max(scores)) # 96
print("最低分:", np.min(scores)) # 78
print("平均分:", np.mean(scores)) # 87.8
print("中位数:", np.median(scores)) # 88.0
print("标准差:", np.std(scores)) # 6.4
print("总和:", np.sum(scores)) # 439向量化运算
NumPy的向量化运算是其最大优势:
scores = np.array([85, 92, 78, 96, 88])
# 每个学生加5分
bonus_scores = scores + 5
print("加分后:", bonus_scores) # [90, 97, 83, 101, 93]
# 每个学生成绩乘以1.1
improved_scores = scores * 1.1
print("提高后:", improved_scores) # [93.5, 101.2, 85.8, 105.6, 96.8]
# 平方运算
squared_scores = scores ** 2
print("平方:", squared_scores) # [7225, 8464, 6084, 9216, 7744]5. 条件筛选
布尔索引
scores = np.array([85, 92, 78, 96, 88])
# 找出90分以上的成绩
excellent_scores = scores[scores >= 90]
print("优秀成绩:", excellent_scores) # [92, 96]
# 找出80-90分的成绩
good_scores = scores[(scores >= 80) & (scores < 90)]
print("良好成绩:", good_scores) # [85, 88]
# 找出不及格的成绩
fail_scores = scores[scores < 60]
print("不及格成绩:", fail_scores) # [] (空数组)多条件筛选
scores = np.array([85, 92, 78, 96, 88])
# 使用逻辑运算符
# & 表示且,| 表示或,~ 表示非
# 大于85且小于95的成绩
selected = scores[(scores > 85) & (scores < 95)]
print("85-95分:", selected) # [92, 88]
# 小于80或大于90的成绩
extreme = scores[(scores < 80) | (scores > 90)]
print("极端成绩:", extreme) # [78, 96]6. 多维数组
创建二维数组
# 5个学生,2门科目的成绩矩阵
score_matrix = np.array([
[85, 90], # 学生1: 数学85, 英语90
[92, 85], # 学生2: 数学92, 英语85
[78, 92], # 学生3: 数学78, 英语92
[96, 78], # 学生4: 数学96, 英语78
[88, 95] # 学生5: 数学88, 英语95
])
print("成绩矩阵:")
print(score_matrix)
print("矩阵形状:", score_matrix.shape) # (5, 2)二维数组操作
# 选择特定行和列
print("第一个学生成绩:", score_matrix[0]) # [85, 90]
print("所有学生的数学成绩:", score_matrix[:, 0]) # [85, 92, 78, 96, 88]
print("所有学生的英语成绩:", score_matrix[:, 1]) # [90, 85, 92, 78, 95]
# 按科目统计
math_scores = score_matrix[:, 0]
english_scores = score_matrix[:, 1]
print("数学平均分:", np.mean(math_scores)) # 87.8
print("英语平均分:", np.mean(english_scores)) # 88.07. 数组拼接和变形
数组拼接
math_scores = np.array([85, 92, 78])
english_scores = np.array([90, 85, 92])
# 水平拼接(按列)
combined = np.hstack([math_scores, english_scores])
print("水平拼接:", combined) # [85, 92, 78, 90, 85, 92]
# 垂直拼接(按行)
score_pairs = np.vstack([math_scores, english_scores])
print("垂直拼接:")
print(score_pairs)
# [[85, 92, 78]
# [90, 85, 92]]数组变形
scores = np.array([85, 92, 78, 96, 88, 90])
# 改变数组形状
reshaped = scores.reshape(2, 3) # 2行3列
print("变形后:")
print(reshaped)
# [[85, 92, 78]
# [96, 88, 90]]
# 展平数组
flattened = reshaped.flatten()
print("展平后:", flattened) # [85, 92, 78, 96, 88, 90]8. 随机数生成
常用随机函数
# 生成随机整数
random_scores = np.random.randint(60, 101, 10) # 10个60-100的随机数
print("随机成绩:", random_scores)
# 生成随机小数
random_floats = np.random.random(5) # 5个0-1的随机小数
print("随机小数:", random_floats)
# 正态分布随机数
normal_scores = np.random.normal(80, 10, 20) # 均值80,标准差10
print("正态分布成绩:", normal_scores[:5]) # 显示前5个📋 成绩分析器完整代码解析
让我们看看项目中的关键代码:
import numpy as np
def create_student_scores():
"""创建学生成绩数组"""
scores = np.array([85, 92, 78, 96, 88, 75, 90, 82, 79, 95])
return scores
def score_analysis(scores):
"""成绩分析"""
# 成绩等级划分
excellent = scores[scores >= 90] # 优秀
good = scores[(scores >= 80) & (scores < 90)] # 良好
pass_score = scores[(scores >= 60) & (scores < 80)] # 及格
fail = scores[scores < 60] # 不及格
# 统计信息
total_students = len(scores)
pass_rate = (total_students - len(fail)) / total_students * 100
print(f"优秀: {len(excellent)}人")
print(f"良好: {len(good)}人")
print(f"及格: {len(pass_score)}人")
print(f"不及格: {len(fail)}人")
print(f"及格率: {pass_rate:.1f}%")
def main():
"""主程序"""
scores = create_student_scores()
print("=== 成绩分析 ===")
print(f"成绩数组: {scores}")
print(f"最高分: {np.max(scores)}")
print(f"最低分: {np.min(scores)}")
print(f"平均分: {np.mean(scores):.2f}")
score_analysis(scores)
if __name__ == "__main__":
main()🎯 学习要点总结
- 数组创建:
np.array(),np.zeros(),np.ones(),np.arange() - 数组属性:
shape,ndim,size,dtype - 索引切片:
scores[0],scores[:3],scores[-2:] - 数学运算:
max(),min(),mean(),median(),std(),sum() - 向量化运算:数组直接进行
+,-,*,/运算 - 条件筛选:
scores[scores >= 90], 使用&,|,~运算符 - 多维数组:二维数组的创建和操作
- 数组操作:拼接、变形、随机数生成
💡 练习建议
- 运行代码:打开
code/第二阶段/2.1_成绩分析器.py体验功能 - 修改数据:尝试不同的成绩数据,观察分析结果
- 添加功能:实现更多统计指标(如方差、百分位数)
- 扩展应用:将分析器应用到其他数据集
- 性能对比:比较NumPy数组和Python列表的运算速度
🚀 NumPy的优势
- 性能:比纯Python代码快10-100倍
- 功能丰富:提供了大量的数学函数
- 内存高效:数组存储更紧凑
- 接口统一:是很多科学计算库的基础
🚀 下一步
掌握NumPy后,你可以继续学习:
- 2.2 Pandas数据分析:处理表格数据
- 2.3 数据可视化:用Matplotlib展示数据
- 第三阶段:机器学习基础
记住:NumPy是数据科学的基石,熟练掌握它会让后续学习事半功倍!
学习愉快!多练习数组操作,这是数据科学的基础技能!